package com.masterclient.app.businessmodule.homemodule.view.adapter.banner;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.eoner.baselibrary.utils.LinearGradientUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.UtilCollection;
import com.eoner.baselibrary.widget.PicassoImageLoader;
import com.eoner.commonbean.banner.BannerNewItemBean;
import com.masterclient.app.R;
import com.masterclient.app.businessmodule.homemodule.bean.banner.BannerNewBean;
import com.masterclient.app.businessmodule.homemodule.bean.hot.HotSearchWordBean;
import com.masterclient.app.businessmodule.homemodule.old.EventAdDataCallback;
import com.masterclient.app.businessmodule.homemodule.view.holder.HomeViewHolder;
import com.masterclient.app.modules.search.SearchResultActivity;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.UIndicator;
import com.gyf.immersionbar.ImmersionBar;
import com.umeng.analytics.MobclickAgent;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;


public class PageXBannerAdapter extends DelegateAdapter.Adapter<HomeViewHolder>  {

    private Context mContext;
    private LayoutHelper mLayoutHelper;
    private VirtualLayoutManager.LayoutParams mLayoutParams;
    private int mCount = 0;
    private BannerNewBean bannerBean;
    private List<HotSearchWordBean> hotWords;
    private EventAdDataCallback eventAdDataCallback;
    private int banner_index;
    private int prePositionOffsetPixels = 0;
    private ColorCallBack colorCallBack;
    private  Banner advBanner;
    private boolean hasBannerBg = false;

    public void setEventAdDataCallback(EventAdDataCallback eventAdDataCallback) {
        this.eventAdDataCallback = eventAdDataCallback;
    }

    public interface ColorCallBack{
        void color_change(int color);
    }

    public PageXBannerAdapter(Context context, LayoutHelper layoutHelper, int count, @NonNull VirtualLayoutManager.LayoutParams layoutParams, BannerNewBean bannerBean, List<HotSearchWordBean> hotWords, ColorCallBack colorCallBack) {
        this.mContext = context;
        this.mLayoutHelper = layoutHelper;
        this.mCount = count;
        this.mLayoutParams = layoutParams;
        this.bannerBean = bannerBean;
        this.colorCallBack = colorCallBack;
        if (hotWords != null) {
            this.hotWords = hotWords;
        } else {
            this.hotWords = new ArrayList<>();
        }
        hasBannerBg = bannerBean != null && bannerBean.getBg_image() != null
                && !TextUtils.isEmpty(bannerBean.getBg_image().getUrl());

    }
    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mLayoutHelper;
    }
    @Override
    protected void onBindViewHolderWithOffset(HomeViewHolder holder, int position, int offsetTotal) {
    }

    @Override
    public HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    public void stopAutoPlay() {
        if (advBanner != null) {
            advBanner.stopAutoPlay();
        }
    }

    @Override
    public void onBindViewHolder(HomeViewHolder holder, int position) {
        if(mLayoutParams!=null) {
            holder.itemView.setLayoutParams(
                    new VirtualLayoutManager.LayoutParams(mLayoutParams));
        }

        //背景图
        if (hasBannerBg) {
            FrameLayout bgLayout = holder.itemView.findViewById(R.id.banner_bg_layout);
            bgLayout.getLayoutParams().height = dp2px(44+177+100) + ImmersionBar.getStatusBarHeight((Activity)mContext);
            ImageView iv = holder.itemView.findViewById(R.id.banner_bg);
            Glide.with(mContext).load(bannerBean.getBg_image().getUrl()).apply(new RequestOptions().centerInside())
                    .into(iv);

        }

        View item = holder.itemView.findViewById(R.id.item);
        advBanner = holder.itemView.findViewById(R.id.advBanner);
        UIndicator uIndicator = holder.itemView.findViewById(R.id.indicator1);

        if(bannerBean != null){
            List<BannerNewItemBean> banners = bannerBean.getList();
            List<String> imgUrls = new ArrayList<String>();
            List<String> imgBgs = new ArrayList<String>();
            if (banners != null) {
                for (BannerNewItemBean shBannerBean : banners) {
                    imgUrls.add(shBannerBean.getImage());
                    imgBgs.add(shBannerBean.getBg_color());
                }

                advBanner.setOffscreenPageLimit(imgUrls.size());
                banner_index = 0;
                if(imgUrls.size() > 0){
                    uIndicator.attachToViewPager(imgUrls.size());
                    uIndicator.onViewPageSelected(0);
                }
                //设置banner样式
                advBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                //设置图片加载器
                advBanner.setImageLoader(new PicassoImageLoader(ScreenUtils.getScreenWidth(), ScreenUtils.dp2px(210)));
                //设置图片集合
                advBanner.setImages(imgUrls);
                //设置banner动画效果
                advBanner.setBannerAnimation(Transformer.Stack);
                //设置自动轮播，默认为true
                advBanner.isAutoPlay(true);
                //设置轮播时间
                advBanner.setDelayTime(5000);
                //设置指示器位置（当banner模式中有指示器时）
                advBanner.setIndicatorGravity(BannerConfig.CENTER);
                //banner设置方法全部调用完毕时最后调用
                advBanner.start();
                // 设置点击事件
                List<BannerNewItemBean> finalBanners = banners;
                advBanner.setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {
                        MobclickAgent.onEvent(mContext, "click_banner");
                        BannerNewItemBean banner = finalBanners.get(position);
                        eventAdDataCallback.adData(banner.getS_ad_name(),banner.getS_ad_id(),banner.getS_group_name(),banner.getS_group_id(),
                                banner.getTarget(), banner.getTarget_id(),position+"");
                        CommonUtil.goNewAnyWhere(mContext,banner.getTarget_platform(),banner.getTarget_message(), banner.getTarget(), banner.getTarget_id(), banner.getImage(), banner.getS_ad_name(), banner.getS_ad_id());
                    }
                });
                String temp_color = "#DAAD8E";
                if(imgBgs.size() > 0){
                    temp_color = imgBgs.get(0);
                }
                if(!UtilCollection.isColor(temp_color)){
                    temp_color = "#DAAD8E";
                }
                if (temp_color != null) {
                    colorCallBack.color_change(Color.parseColor(temp_color));
                }
                advBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        if(positionOffsetPixels == 0) {
                            prePositionOffsetPixels = positionOffsetPixels;
                            try {
                                    if (UtilCollection.isColor(imgBgs.get(banner_index))) {
                                        if (!hasBannerBg) {
//                                            item.setBackgroundColor(Color.parseColor(imgBgs.get(banner_index)));
                                        }
                                        colorCallBack.color_change(Color.parseColor(imgBgs.get(banner_index)));
                                    }
                            } catch (Exception e){
                                e.printStackTrace();
                            }
                            return;
                        }
                        try {
                            int startColor = 0;
                            int endColor = 0;
                            int start = 0;
                            int end = 0;
                            start = position;
                            if(positionOffsetPixels > prePositionOffsetPixels){//从左往右滑动
                                if(position == imgBgs.size() - 1){
                                    end = 0;
                                }else{
                                    end = (position + 1);
                                }
                                //System.out.println(banner_index + "------- > 从左往右滑动"  + start + "," + end);
                            }else if(positionOffsetPixels < prePositionOffsetPixels){
                                if(position == 0){
                                    end = imgBgs.size() -1;
                                }else{
                                    end = position - 1;
                                }
                                //System.out.println(banner_index + "------- > 从右往左滑动" + start + "," + end);
                            }else{
                                return;
                            }
//                                    System.out.println("start color ------- > " + imgBgs.get(start));
//                                    System.out.println("end color ------- > " + imgBgs.get(end));

                            if(UtilCollection.isColor(imgBgs.get(start))){
                                startColor = Color.parseColor(imgBgs.get(start));
                            }else{
                                startColor = Color.parseColor("#DAAD8E");
                            }


                            if(UtilCollection.isColor(imgBgs.get(end))){
                                endColor = Color.parseColor(imgBgs.get(end));
                            }else{
                                endColor = Color.parseColor("#DAAD8E");
                            }
                            //System.out.println("start ------- > " + start + "end ------- > " +  end + "positionOffset ------- >" + positionOffset);
                            //if(positionOffset < 0.4)
                                if (UtilCollection.isColor(imgBgs.get(banner_index))) {
                                    if (!hasBannerBg) {
//                                    item.setBackgroundColor(LinearGradientUtil.getColor(startColor, endColor, positionOffset * 1f));
                                    }
                                    colorCallBack.color_change(LinearGradientUtil.getColor(startColor, endColor, positionOffset * 1f));
                                }

                            prePositionOffsetPixels = positionOffsetPixels;
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onPageSelected(int position) {
                        //System.out.println("position ------- > " + position);
                        advBanner.setVisibility(View.VISIBLE);
                        int cur = position + 1;

                        //cur = (cur == 0 ? imgUrls.size() : cur);

                        if (uIndicator != null){
                            uIndicator.onViewPageSelected(position);
                        }

                        //if(banner_index == cur - 1) return;
                        banner_index = cur - 1;
                        prePositionOffsetPixels = 0;
                            try {
                                if (UtilCollection.isColor(imgBgs.get(cur - 1))) {
                                    //head_view.setBackgroundColor(Color.parseColor(imgBgs.get(cur - 1)));
                                    //System.out.println("banner_index ------- > " + banner_index);
                                } else {
                                    if (UtilCollection.isColor(imgBgs.get(banner_index))) {
                                        if (!hasBannerBg) {
//                                            item.setBackgroundColor(Color.parseColor("#DAAD8E"));
                                        }
                                        colorCallBack.color_change(Color.parseColor("#DAAD8E"));
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                if (UtilCollection.isColor(imgBgs.get(banner_index))) {
                                    if (!hasBannerBg){
//                                        item.setBackgroundColor(Color.parseColor("#DAAD8E"));
                                }
                                    if (colorCallBack != null) {
                                        colorCallBack.color_change(Color.parseColor("#DAAD8E"));
                                    }
                                }
                            }
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }
        }
        item.setPadding(0,0,0,0);
    }

    private void onClickHotWord(HotSearchWordBean hotWord, int position) {
        try {
            if(TextUtils.isEmpty(hotWord.getTarget())){
                Intent intent = new Intent(mContext, SearchResultActivity.class);
                intent.putExtra("keyword",hotWord.getSearch_word());
                intent.putExtra("search_type","推荐词");
                mContext.startActivity(intent);
            }else {
                CommonUtil.goNewAnyWhere(mContext,hotWord.getTarget_platform(),hotWord.getTarget_message(), hotWord.getTarget(), hotWord.getTarget_id(), "", "", "");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return mCount;
    }

    @Override
    public int getItemViewType(int position) {
        return 2;
    }

}
